<template>
	<el-dialog v-model="dialogVisible" width="45%" title="修改密码" :before-close="handleClose">
		<div style="font-size: 14px; line-height: 30px" size="default">
			<el-form :model="form" label-width="100px" ref="formRef" :rules="rules">
				<el-form-item label="输入密码：" prop="password">
					<el-input type="password" show-password v-model="form.password" placeholder="输入用户密码" style="min-width: 300px"></el-input>
				</el-form-item>
				<el-form-item label="确认密码：" prop="confirmPassword">
					<el-input type="password" show-password v-model="form.confirmPassword" placeholder="请确认输入密码" style="min-width: 300px"></el-input>
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" @click="submit">提交</el-button>
				<el-button @click="handleClose">关闭</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script lang="ts" setup>
import { ref, watch, reactive } from 'vue';
import { editPwd } from '/@/api/api';
import { ElMessage } from 'element-plus';

const dialogVisible = ref(false);
const form = ref({});
const formRef = ref();

const props = defineProps({
	dialogVisible: {
		type: Boolean,
		default: () => false,
	},
	row: {
		type: Object,
		default: () => {},
	},
});

const equalToPassword = (rule, value, callback) => {
	if (form.value.password !== value) {
		callback(new Error('两次输入的密码不一致'));
	} else {
		callback();
	}
};
// 表单验证
const rules = reactive({
	password: [
		{ required: true, message: '密码不能为空', trigger: 'blur' },
		{ min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
		{
			pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{8,}$/,
			message: '密码需要包含大小写字母和数字且至少8位',
			trigger: 'blur',
		},
	],
	confirmPassword: [
		{ required: true, message: '确认密码不能为空', trigger: 'blur' },
		{ required: true, validator: equalToPassword, trigger: 'blur' },
	],
});

watch(
	() => props.dialogVisible,
	(val) => {
		// console.log(props.dialogVisible)
		// if (val) {

		dialogVisible.value = props.dialogVisible;
		// }
	}
);

// 提交
const submit = () => {
	formRef.value.validate(async (valid) => {
		if (valid) {
			// console.log(props.row);
			let { id } = props.row;
			let { password } = form.value;
			const { code } = await editPwd({
				userId: id,
				password,
			});
			if (code === 200) {
				ElMessage.success('修改成功');
				handleClose();
			}
		}
	});
};

// 关闭
const emit = defineEmits(['ChangePwdClose']);
function handleClose() {
	form.value = {};
	formRef.value.resetFields();
	emit('ChangePwdClose');
}
</script>
